package com.github.postsanf.yinian.activity;

import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.flaviofaria.kenburnsview.KenBurnsView;
import com.flaviofaria.kenburnsview.RandomTransitionGenerator;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.TimeMarks;
import com.github.postsanf.yinian.bean.YNResponse;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.widget.MarqueeView;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class TimeMarksDetileActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_back;
    private KenBurnsView time_mark_edit_bg;
    private List<TimeMarks.DataBean> timeMarks;
    private int position;
    private TextView tv_days;
    private MarqueeView mv_days;
    private int days;
    private MarqueeView mv_days_one;
    private SimpleDraweeView sd_head;
    private TextView tv_time_top;
    private TextView tv_title;
    private ImageView iv_bg;
    private TextView tv_edit;
    private LinearLayout ll_edit;
    private LinearLayout ll_download;
    private LinearLayout ll_deleted;
    private LinearLayout ll_share;
    private LinearLayout ll_creat;
    private TextView tv_download;
    private TextView tv_deleted;
    private TextView tv_creat;
    private ImageView iv_weixin;
    private ImageView iv_pengyouquan;
    private ImageView iv_qq;
    private String headUrl;
    private ProgressDialog mProgressDialog;
    private Bitmap mbitmap;
    private RelativeLayout activity_time_marks_detile;
    private File f;
    private LinearLayout ll_days;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_marks_detile);
        registBroadcastReceiver();
        initData();
        initView();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            timeMarks = (List<TimeMarks.DataBean>) intent.getSerializableExtra("timeMarks");
            position = intent.getIntExtra("position", 0);
            days = intent.getIntExtra("day", 0);
            headUrl = timeMarks.get(position).getUpic();
        }
    }

    private void initView() {
        iv_back = ((ImageView) findViewById(R.id.iv_back));
        iv_bg = ((ImageView) findViewById(R.id.iv_bg));
        ll_edit = ((LinearLayout) findViewById(R.id.ll_edit));
        ll_download = ((LinearLayout) findViewById(R.id.ll_download));
        ll_deleted = ((LinearLayout) findViewById(R.id.ll_deleted));
        ll_share = ((LinearLayout) findViewById(R.id.ll_share));
        ll_creat = ((LinearLayout) findViewById(R.id.ll_creat));

        tv_edit = ((TextView) findViewById(R.id.tv_edit));
        tv_download = ((TextView) findViewById(R.id.tv_download));
        tv_deleted = ((TextView) findViewById(R.id.tv_deleted));
        tv_creat = ((TextView) findViewById(R.id.tv_creat));
        iv_weixin = ((ImageView) findViewById(R.id.iv_weixin));
        iv_pengyouquan = ((ImageView) findViewById(R.id.iv_pengyouquan));
        iv_qq = ((ImageView) findViewById(R.id.iv_qq));
        activity_time_marks_detile = ((RelativeLayout) findViewById(R.id.activity_time_marks_detile));
        ll_days = ((LinearLayout) findViewById(R.id.ll_days));

        iv_back.setOnClickListener(this);
        iv_bg.setOnClickListener(this);
        tv_edit.setOnClickListener(this);
        tv_download.setOnClickListener(this);
        tv_deleted.setOnClickListener(this);
        tv_creat.setOnClickListener(this);
        iv_weixin.setOnClickListener(this);
        iv_pengyouquan.setOnClickListener(this);
        iv_qq.setOnClickListener(this);

        time_mark_edit_bg = ((KenBurnsView) findViewById(R.id.time_mark_edit_bg));
        time_mark_edit_bg.setTransitionGenerator(new RandomTransitionGenerator(10000, new LinearInterpolator()));
        ImageLoader.getInstance().displayImage(timeMarks.get(position).getMarkPic(), time_mark_edit_bg, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                mbitmap = bitmap;
            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });
        tv_days = ((TextView) findViewById(R.id.tv_days));
        mv_days = ((MarqueeView) findViewById(R.id.mv_days));
        mv_days_one = ((MarqueeView) findViewById(R.id.mv_days_one));
        sd_head = ((SimpleDraweeView) findViewById(R.id.sd_head));
        ImageOptHelper.showFrescoAvatar(Uri.parse(headUrl), sd_head, this);

        tv_time_top = ((TextView) findViewById(R.id.tv_time_top));
        tv_time_top.setText(timeMarks.get(position).getMarkDate());

        tv_title = ((TextView) findViewById(R.id.tv_title));
        tv_title.setText(timeMarks.get(position).getMarkContent());

        List<String> items = new ArrayList<>();
        List<String> itemsOne = new ArrayList<>();
        items.add(days + "");
        itemsOne.add("DAYS");
        if (days > 30) {
            //多少月多少日
            int month = days / 30;
            int day = days % 30;
            //多少年多少月多少日
            int year = days / 365;
            int month1 = days % 365 / 30;
            int day1 = days % 365 % 30;
            if (month > 0) {
                if (day > 0) {
                    items.add(month + "\n" + day);
                    itemsOne.add("MONTHS" + "\n" + "\n" + "DAYS");
                } else {
                    items.add(month + " " + "MONTHS");
                    itemsOne.add("MONTHS");
                }
            }
            if (year > 0) {
                if (day1 > 0) {
                    items.add(year + "\n" + month1 + "\n" + day1);
                    itemsOne.add("YEARS" + "\n" + "\n" + "MONTHS" + "\n" + "\n" + "DAYS");
                } else if (month1 > 0) {
                    items.add(year + "\n" + month1);
                    itemsOne.add("YEARS" + "\n" + "\n" + "MONTHS");
                } else {
                    items.add(year + "");
                    itemsOne.add("YEARS");
                }
            }
        }
        mv_days.startWithList(items);
        mv_days_one.startWithList(itemsOne);
    }

    public void saveBitmap(View v, int flag) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        f = new File(file.getPath() + "/", System.currentTimeMillis() + ".png");
        url = "file://" + f.getPath();
        if (f.exists()) {
            f.delete();
        }
        Bitmap bm = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        v.draw(canvas);
        if (flag == 6) {
            new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withMedia(new UMImage(this, bm))
                    .share();
        } else if (flag == 7) {
            new ShareAction(this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withMedia(new UMImage(this, bm))
                    .share();
        } else {
            new ShareAction(this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                    .withMedia(new UMImage(this, bm))
                    .share();
        }
    }


    private void registBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTIONs.ModifyTimeMarks);
        intentFilter.addAction(ACTIONs.TimeMarks);
        registerReceiver(MyReceiver, intentFilter);
    }

    BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.ModifyTimeMarks:
                    timeMarks = ((List<TimeMarks.DataBean>) intent.getSerializableExtra("modifyTimeMarks"));
                    position = intent.getIntExtra("position", 0);
                    days = getMiltime(timeMarks.get(0).getMarkDate(), timeMarks.get(0).getMarkRepeat());
                    initView();
                    break;
                case ACTIONs.TimeMarks:
//                    timeMarks = ((List<TimeMarks.DataBean>) intent.getSerializableExtra("addTimeMarks"));
//                    position = intent.getIntExtra("position", 0);
//                    days = getMiltime(timeMarks.get(0).getMarkDate(), timeMarks.get(0).getMarkRepeat());
//                    initView();
                    break;
            }
        }
    };

    private boolean enter = false;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    enterAndExitAnimation(ll_edit, 200, enter);
                    break;
                case 2:
                    enterAndExitAnimation(ll_download, 200, enter);
                    break;
                case 3:
                    enterAndExitAnimation(ll_deleted, 200, enter);
                    break;
                case 4:
                    enterAndExitAnimation(ll_share, 240, enter);
                    break;
                case 5:
                    enterAndExitAnimation(ll_creat, 200, enter);
                    break;
                case 6:
                    saveBitmap(activity_time_marks_detile, 6);
                    break;
                case 7:
                    saveBitmap(activity_time_marks_detile, 7);
                    break;
                case 8:
                    saveBitmap(activity_time_marks_detile, 8);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_bg:
                enter = !enter;
                handler.sendEmptyMessage(1);
                handler.sendEmptyMessageDelayed(2, 100);
                handler.sendEmptyMessageDelayed(3, 200);
                handler.sendEmptyMessageDelayed(4, 300);
                handler.sendEmptyMessageDelayed(5, 400);
                break;
            case R.id.tv_edit:
                if (String.valueOf(application.getCurID()).equals(timeMarks.get(0).getUserid())) {
                    startActivity(new Intent(TimeMarksDetileActivity.this, CreatTimeMarksActivity.class).putExtra("edit", timeMarks.get(position)));
                    enter = !enter;
                    enterAndExitAnimation(ll_edit, 200, false);
                    enterAndExitAnimation(ll_download, 200, false);
                    enterAndExitAnimation(ll_deleted, 200, false);
                    enterAndExitAnimation(ll_share, 240, false);
                    enterAndExitAnimation(ll_creat, 200, false);
                } else {
                    showToast("只有该条纪念日的创建者才能编辑");
                }
                break;
            case R.id.tv_download:
                downLoad();
                break;
            case R.id.tv_deleted:
                if (String.valueOf(application.getCurID()).equals(timeMarks.get(0).getUserid())) {
                    deleteTimeMarks();
                } else {
                    showToast("只有该条纪念日的创建者才能删除");
                }
                break;
            case R.id.tv_creat:
                startActivity(new Intent(TimeMarksDetileActivity.this, CreatTimeMarksActivity.class));
                finish();
                break;
            case R.id.iv_weixin:
                mv_days.setVisibility(View.GONE);
                mv_days_one.setVisibility(View.GONE);
                tv_time_top.setVisibility(View.VISIBLE);
                tv_title.setVisibility(View.VISIBLE);
                sd_head.setVisibility(View.VISIBLE);
                ll_days.setVisibility(View.VISIBLE);
                tv_days.setText(String.valueOf(days));
                handler.sendEmptyMessageDelayed(6, 50);
                break;
            case R.id.iv_pengyouquan:
                mv_days.setVisibility(View.GONE);
                mv_days_one.setVisibility(View.GONE);
                tv_time_top.setVisibility(View.VISIBLE);
                tv_title.setVisibility(View.VISIBLE);
                sd_head.setVisibility(View.VISIBLE);
                ll_days.setVisibility(View.VISIBLE);
                tv_days.setText(String.valueOf(days));
                handler.sendEmptyMessageDelayed(7, 50);
                break;
            case R.id.iv_qq:
                mv_days.setVisibility(View.GONE);
                mv_days_one.setVisibility(View.GONE);
                tv_time_top.setVisibility(View.VISIBLE);
                tv_title.setVisibility(View.VISIBLE);
                sd_head.setVisibility(View.VISIBLE);
                ll_days.setVisibility(View.VISIBLE);
                tv_days.setText(String.valueOf(days));
                handler.sendEmptyMessageDelayed(8, 50);
                break;
        }
    }

    private void downLoad() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File yinianfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
                if (!(yinianfile.mkdir() || yinianfile.isDirectory())) {
                    yinianfile.mkdirs();
                }
                File file = new File(Environment.getExternalStorageDirectory() + "/yinian/YiNian", System.currentTimeMillis() + ".png");
                try {
                    URL url = new URL(timeMarks.get(position).getMarkPic());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(500);
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        FileOutputStream fos = new FileOutputStream(file);
                        int len = 0;
                        byte[] buff = new byte[1024];
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                        }
                        is.close();
                        fos.close();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("下载成功！！！");
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void deleteTimeMarks() {
        mProgressDialog = ProgressDialog.show(this, "", "");
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.MARKID, timeMarks.get(position).getMarkID());
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynDeleteTimeMark))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNResponse ynResponse = gson.fromJson(s, YNResponse.class);
                        if (TextUtils.equals(ynResponse.getMsg(), "success")) {
                            sendBroadcast(new Intent(ACTIONs.DeleteTimeMarks));
                            finish();
                        }
                        mProgressDialog.dismiss();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void enterAndExitAnimation(View view, int value, boolean enterAni) {
        if (enterAni) {
            view.setVisibility(View.VISIBLE);
            mv_days.setVisibility(View.GONE);
            mv_days_one.setVisibility(View.GONE);
            tv_time_top.setVisibility(View.GONE);
            tv_title.setVisibility(View.GONE);
            sd_head.setVisibility(View.GONE);
            AnticipateOvershootInterpolator anticipateOvershootInterpolator = new AnticipateOvershootInterpolator();
            ObjectAnimator ta2 = ObjectAnimator.ofFloat(view, "translationX", UIHelper.dip2px(this, -value), UIHelper.dip2px(this, 17));
            ta2.setDuration(1000);
            ta2.setInterpolator(anticipateOvershootInterpolator);
            ta2.start();
        } else {
            ll_days.setVisibility(View.GONE);
            mv_days.setVisibility(View.VISIBLE);
            mv_days_one.setVisibility(View.VISIBLE);
            tv_time_top.setVisibility(View.VISIBLE);
            tv_title.setVisibility(View.VISIBLE);
            sd_head.setVisibility(View.VISIBLE);
            ObjectAnimator ta2 = ObjectAnimator.ofFloat(view, "translationX", UIHelper.dip2px(this, 17), UIHelper.dip2px(this, -value));
            ta2.setDuration(500);
            ta2.start();
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(TimeMarksDetileActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(TimeMarksDetileActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(TimeMarksDetileActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(TimeMarksDetileActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    private int getMiltime(String time, String repeat) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        long timeMil = 0;
        try {
            Date parse = simpleDateFormat.parse(time);
            timeMil = parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long currentTime = getCurrentTime();
        long diffMills = currentTime - timeMil;
        int days;
        if (repeat.equals("1") && diffMills > 0) {
//            int i = (int) (diffMills / 1000 / 3600 / 24) / 365;
//            int n = (int) (diffMills / 1000 / 3600 / 24) - 365 * i;
//            if (i > 0) {
//                days = n * (-1) + 365 + 1;
//            } else {
//                days = n * (-1) + 365;
//            }
            long currentMillis = System.currentTimeMillis();
            Date curDate = new Date(currentMillis);
            String time1 = simpleDateFormat.format(curDate);
            String[] split = time1.split("-");
            int yearInt = Integer.parseInt(split[0]) + 1;
            String[] split1 = time.split("-");
            time = String.valueOf(yearInt) + split1[1] + split1[2];
            try {
                Date parse = simpleDateFormat.parse(time);
                timeMil = parse.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            diffMills = currentTime - timeMil;
        }
        diffMills = Math.abs(diffMills);
        days = (int) (diffMills / 1000 / 3600 / 24);
        return days;
    }

    private Long getCurrentTime() {
        long currentMillis = System.currentTimeMillis();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(currentMillis);
        String time = formatter.format(curDate);

        long timeMil = 0;
        try {
            Date parse = formatter.parse(time);
            timeMil = parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeMil;
    }

    private String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String format = simpleDateFormat.format(date);
        return format;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(MyReceiver);
        super.onDestroy();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
